﻿#region | Copyright © 2556 |

/*
##########################################################################
	Author By : Siriwat Suananpornpanit
	DateTime : 2556/08/30
##########################################################################
*/

#endregion

#region | Imports |

using System;
using System.Collections.Generic;
using DataAccess;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using Web.Business;
using Web.Core;
using Exception = System.Exception;

#endregion

namespace Web.Pages
{
    public partial class Application : System.Web.UI.Page
    {

        #region | Event Paging |

        #region | Const |

        private DataAccessClient dal = new DataAccessClient(DATABASE_PROXY.AUTH);

        private p_USER_PROFILE _userPartial;//= Core.SessionPool.GetInstance().GetSession();

        private Int32 idx = 1;

        private string _err;

        #endregion

        #region | InitAccess |

        public void InitAccess()
        {
            try
            {
                // Init Access
                AccessToolbar.Resource = "Resource";
                //
                AccessToolbar.AddText = "Add";
                AccessToolbar.EditText = "Edit";
                AccessToolbar.CopyText = "Copy";
                AccessToolbar.DeleteText = "Delete";
                AccessToolbar.SearchText = "Search";
                //
                AccessToolbar.SaveVisible = false;
                AccessToolbar.CancelVisible = false;
                AccessToolbar.AddClick += OnAddClick;
                AccessToolbar.EditClick += OnEditClick;
                AccessToolbar.CopyClick += OnCopyClick;
                AccessToolbar.DeleteClick += OnDeleteClick;
                AccessToolbar.SearchClick += OnSearchClick;
            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
        }

        private void OnSearchClick(object sender, EventArgs e)
        {
            // GridView Reload 
           OnReload();
        }

        private void OnDeleteClick(object sender, EventArgs e)
        {
            // Response.Write("Delete");
            string[] applNo= new string[grvResult.PageCount];
            Int32 idxKey = 0;
            for (Int32 i = 0; i <= grvResult.PageCount; i += 1)
            {
                ASPxCheckBox chk =
                    grvResult.FindRowCellTemplateControl(i, grvResult.Columns["Check"] as GridViewDataColumn,
                        "chk") as ASPxCheckBox;

                if (chk != null)
                    if (chk.Checked)
                    {
                        applNo[idxKey] = grvResult.GetRowValues(i, "APPLNO").ToString();
                        idxKey += 1;
                    }

            }

            if (idxKey == 0)
                OnToggleModal(
                           modal: ModalFlag.Hide, 
                           messageBox: MessageFlag.Wraning, 
                           massage: ResourceTools.GetResource(resourceKey: "SpecifyIsOneRec"));
            else
            {
                for (int i = 0; i <= idxKey; i++)
                {
                    if (!String.IsNullOrEmpty((String)(applNo[i])))
                    {
                        ApplicationBal.GetInstance().Delete(
                            new p_APPLICATION()
                            {
                                COMPANY_CODE = _userPartial.COMP_CODE
                                ,
                                APPLNO = (String)applNo[i]
                            }, out _err);
                        if (!String.IsNullOrEmpty(_err))
                        {
                            //
                            Core.Modal.Exception(
                               page: this.Page,
                               message: Core.Exception.ModalException(
                                                   method: System.Reflection.MethodBase.GetCurrentMethod(),
                                                   ex: new Exception(string.Format(
                                                    @"checked rows is {0} it have solve in underline.
                                                    <br/><br/>{1}"
                                                    , i
                                                    , _err))));
                            //
                            
                            return;
                        }
                    }
                    
                }
            }


        }

        private void OnCopyClick(object sender, EventArgs e)
        {
            try
            {
                Int32 result = 0;
                string applNo = null;
                for (Int32 i = 0; i <= grvResult.PageCount; i += 1)
                {
                    ASPxCheckBox chk =
                        grvResult.FindRowCellTemplateControl(i, grvResult.Columns["Check"] as GridViewDataColumn,
                            "chk") as ASPxCheckBox;

                    if (chk != null)
                        if (chk.Checked)
                        {
                            applNo = grvResult.GetRowValues(i, "APPLNO").ToString();
                            result += 1;
                        }

                }

                if (result == 0)
                    OnToggleModal(
                                modal: ModalFlag.Hide,
                                messageBox: MessageFlag.Wraning,
                                massage: ResourceTools.GetResource(resourceKey: "SpecifyIsOneRec"));

                else if (result > 1)
                    OnToggleModal(
                               modal: ModalFlag.Hide, 
                               messageBox:  MessageFlag.Wraning, 
                               massage: ResourceTools.GetResource(resourceKey: "SpecifyIsLastOneRec"));

                else
                {
                    // Show Modal
                    pcModal.HeaderText = ResourceTools.GetResource(resourceKey: "ApplicationAdd");
                    ApplicationModal.OnLoad(
                                           flag: AccessFlag.Copy,
                                           applNo: applNo,
                                           headerText: ResourceTools.GetResource(resourceKey: "ApplicationAdd"),
                                           companyCode: _userPartial.COMP_CODE);
                }

            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
        }

        private void OnEditClick(object sender, EventArgs e)
        {
            try
            {
                Int32 result = 0;
                string applNo = null;
                for (Int32 i = 0; i <= grvResult.PageCount; i += 1)
                {
                    ASPxCheckBox chk =
                        grvResult.FindRowCellTemplateControl(i, grvResult.Columns["Check"] as GridViewDataColumn,
                            "chk") as ASPxCheckBox;

                    if (chk != null)
                        if (chk.Checked)
                        {
                            applNo = grvResult.GetRowValues(i, "APPLNO").ToString();
                            result += 1;
                        }
                }

                if (result == 0)
                    OnToggleModal(
                              modal:  ModalFlag.Hide, 
                              messageBox:  MessageFlag.Wraning, 
                              massage: ResourceTools.GetResource(resourceKey: "SpecifyIsOneRec"));

                else if (result > 1)
                    OnToggleModal( 
                                modal:  ModalFlag.Hide, 
                                messageBox:  MessageFlag.Wraning, 
                                massage:  ResourceTools.GetResource(resourceKey: "SpecifyIsLastOneRec"));

                else
                {
                    // Show Modal
                    pcModal.HeaderText = ResourceTools.GetResource(resourceKey: "ApplicationEdit");
                    ApplicationModal.OnLoad(
                                           flag: AccessFlag.Edit,
                                           applNo: applNo,
                                           headerText: ResourceTools.GetResource(resourceKey: "ApplicationEdit"),
                                           companyCode: _userPartial.COMP_CODE);
                }
            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
            
        }

        private void OnAddClick(object sender, EventArgs e)
        {
            try
            {
                pcModal.HeaderText = ResourceTools.GetResource(resourceKey: "ApplicationAdd");
                ApplicationModal.OnLoad(
                                       flag: AccessFlag.Add,
                                       applNo: null,
                                       headerText: ResourceTools.GetResource(resourceKey: "ApplicationAdd"),
                                       companyCode: _userPartial.COMP_CODE);
            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // Binding Event in Page and Init Session
                Binding();

                //
                if (!this.Page.IsPostBack)
                {
                    // GridView Loading 
                    OnReload();
                }

            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
            
        }

        #endregion

        #region | Methods |
        
        #region | Bind |

        private void Binding()
        {
            // Partial Session
            _userPartial = SessionPool.GetInstance().GetSession(this.Page);

            // Init Controls Access
            InitAccess();

            // Init grvResult as GridView
            grvResult.HtmlRowCreated += GrvResultOnHtmlRowCreated;
            grvResult.PageIndexChanged += GrvResultOnPageIndexChanged;
            grvResult.AfterPerformCallback += GrvResultOnAfterPerformCallback;
            //

        }

        private void GrvResultOnAfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            // GridView Callback 
            OnReload();
        }

        private void GrvResultOnPageIndexChanged(object sender, EventArgs e)
        {
            // GridView Reload and Fixed Paging
            OnReload(grvResult.PageIndex);
        }

        protected void chk_Checked(object sender, EventArgs e)
        {
            GridView.HeaderChecking(
                page: this.Page,
                grvResult: grvResult);
        }

        private void GrvResultOnHtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
        {
            try 
            { 
                if (e.RowType != GridViewRowType.Data) return;

                GridView.OnHtmlRowCreated(
                    page: this.Page,
                    grvResult: grvResult,
                    e: e);
            }
            catch (System.Exception ex)
            {
                //
                Core.Modal.Exception(
                   page: this.Page,
                   message: Core.Exception.ModalException(
                                       method: System.Reflection.MethodBase.GetCurrentMethod(),
                                       ex: ex));
                //
            }
                
        }
        
        #endregion

        #endregion

        #region | Allow Init Permission |

        public void OnToggleModal(
            ModalFlag modal, 
            MessageFlag messageBox, 
            String massage,String 
            headerText = null)
        {
           OnToggleHeaderText(headerText);
           Core.Modal.OnToggleModal(
                control: pcModal
                ,page: this.Page
                ,modalBox: modal
                ,messageBox: messageBox
                ,massage: massage
                , headerText: headerText);
        }

        public void OnToggleHeaderText(String headerText = "[?]")
        {
            pcModal.HeaderText = headerText;
        }

        public void OnReload(Int32 pageiIdx = 0)
        {
            grvResult.BeginUpdate();
            try
            {
                IEnumerable<p_APPLICATION> list = ApplicationBal.GetInstance()
                    .Select(page: this.Page, obj: new p_APPLICATION()
                    {
                        APPLNO = txApplicationNo.Text
                         ,
                        APPLNAME = txApplicationName.Text
                        ,
                        COMPANY_CODE = (String)_userPartial.COMP_CODE
                    });
                grvResult.DataSource = list;
                grvResult.PageIndex = (pageiIdx == 0) ? grvResult.PageIndex : pageiIdx;
                grvResult.DataBind();
            }
            finally
            {
                grvResult.EndUpdate();
            }
        }

        #endregion
    }
}